﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Text;
using NHibernate.Cfg;
using NHibernate;
using log4net;
using NHibernate.Criterion;
using BidFunLib.Entity;
using BidFunLib.DAO;


namespace BidFunLib
{
    /// <summary>
    /// 
    /// </summary>
    class BidSaleDAO 
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(BidSaleDAO));

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public BidSale getBidSaleById(Int32 id)
        {
            BidSale bidSale = null;

            using (ISession session = NHibernateHelper.OpenSession())
            {
                ITransaction transaction = session.BeginTransaction();
                transaction.Begin();
                IList<BidSale> sales = (IList<BidSale>)session.CreateQuery("from BidSale bs where bs.IdBidSale= ?")
                .SetInt32(0, id)
                .List<BidSale>();

                if (sales != null && sales.Count > 0)
                {
                    bidSale = sales.First();
                }
                transaction.Commit();
                session.Close();
                return bidSale;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pseudo"></param>
        /// <returns></returns>
        public BidSale saveOrUpdateBidSale(BidSale bidSale)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                ITransaction transaction = session.BeginTransaction();
                transaction.Begin();
                if (bidSale.IdBidSale== - 1)
                {
                    log.Debug("Saving BidSale " + bidSale.BidFunIdentifier);
                    Int32 newID = (Int32)session.Save(bidSale);
                    bidSale.IdBidSale = newID;
                    log.Debug("BidSale " + bidSale.BidFunIdentifier + " saved !");
                }
                else
                {
                    log.Debug("Updating BidSale " + bidSale.BidFunIdentifier);
                    session.Update(bidSale);
                    log.Debug("BidSale " + bidSale.BidFunIdentifier + " updated !");
                }
                transaction.Commit();
                session.Close();
                return bidSale;
            }
        }


    }
}
